.PHONY : devel build clean distclean install uninstall run buildglibc buildmain

build_dir=build
workdir=workdir
installdir=/${workdir}/${build_dir}/glibc-static
libdir=${installdir}/lib

buildimage :
	sudo docker build -t glibcdbg:latest --build-arg BUILDKIT_INLINE_CACHE=1 .

rmiimage :
	sudo docker rmi glibcdbg:latest

getglibc :
	if [ ! -f ${build_dir}/glibc-2.37.tar.xz ]; then  wget https://fossies.org/linux/misc/glibc-2.37.tar.xz -P ${build_dir}; fi

targlibc : getglibc
	tar -xf ${build_dir}/glibc-2.37.tar.xz -C ${build_dir}
	mkdir -p ${build_dir}/glibc-2.37/build

applypatch : targlibc
	cd ${build_dir}/glibc-2.37 && patch -p1 < ../../glibc-patch/0001-dbg-dbg_printf-__libc_start_main.patch

builddir :
	mkdir -p ${build_dir}/glibc-static

rmdir :
	sudo rm -rf ${build_dir}

buildglibc :
	cd ${build_dir}/glibc-2.37/build && \
	../configure --disable-werror --enable-static --prefix=${installdir} --verbose && \
	make -j16 && make install

cleanglibc :
	cd ${build_dir}/glibc-2.37/build && \
	make distclean && \
	sudo rm -rf ${build_dir}/glibc-static/*

buildmod :
	cd mod && make -j8

cleanmod :
	cd mod && make clean

install :
	cd mod && sudo insmod debug_printf.ko
uninstall :
	cd mod && sudo rmmod debug_printf

buildmain :
	gcc -o ${build_dir}/crt.elf -nostdlib -static test/test.c -L${libdir} \
	${libdir}/crt1.o ${libdir}/crti.o \
	-Wl,--start-group -Wl,-lc -Wl,-lgcc -Wl,-lgcc_eh -Wl,--end-group \
	${libdir}/crtn.o

cleanmain :
	rm -rf ${build_dir}/crt.elf

dockerbuildglibc :
	sudo docker run \
	--volume=${PWD}:/${workdir}:rw \
	--name buildglibc \
	-it glibcdbg:latest \
	make buildglibc ; \
	sudo docker rm buildglibc

dockerbuildmain :
	sudo docker run \
	--volume=${PWD}:/${workdir}:rw \
	--name buildmain \
	-it glibcdbg:latest \
	make buildmain ; \
	sudo docker rm buildmain

devel : buildimage builddir applypatch

build : buildmod dockerbuildglibc dockerbuildmain

clean : cleanglibc cleanmod cleanmain

distclean : cleanmod rmdir rmiimage

run :
	sudo dmesg --clear >> /dev/null && \
	./${build_dir}/crt.elf hello chushi && \
	sudo dmesg 